import React, { Component } from 'react';
import fetch from 'dva/fetch';
import { Table, Popconfirm, message, Form } from 'antd';
import ShowType from '../../../routes/common/showType';
import styles from '../../../index.less';
import * as config from '../../../utils/config';
import * as commonFunc from '../../Common/commonFunc';

class MergeTableEdit extends Component {
  constructor(props) {
    super(props);
    this.state = {
      componentName: props.componentName,
      sTabId: props.sTabId,
      columns: [], /* 合并后的表头 */
      data: [], /* 整合后的数据 */
      pages: { pageNum: 0, totalCount: 0 }, /* 页码 */
      tableConfig: {},
      dataUrl: `${config.server_host}business/getBusinessDataByFormcustomId/${props.config.sId}?sModelsId=${props.formId}`, /* 请求业务数据地址 */
      selectedRowKeys: [], /* 选择数据 */
      // selectedFieldKey: '',
      // BtnOperations: '', /* 表头里面的操作 */
      // BtnAdd: '', /* 新增 */
      // BtnRefresh: '', /* 刷新 */
      // BtnUpd: '', /* 修改 */
      // BtnDel: '', /* 删除 */
      // BtnSave: '', /* 保存 */
      // BtnCancel: '', /* 取消 */
      // BtnSetPeriod: '', /* 设置期初 */
      // BtnRelievePeriod: '', /* 解除锁定 */
      isAdd: false,
      isEdit: false,
      // addisabled: false,
      // sId: '',
      mergeConfig: [], /* 显示的组件配置 */
      sActiveId: props.sActiveId,
      disabledKey: '', /* 正在编辑的行Key值 */
      dataRequired: {}, /* 必填字段 */
      // isShow: 'none',
      scrollX: props.scrollX,
    };
  }

  componentWillMount() {
    const { gdsconfigformslave } = this.props.config;
    const { gdsformconst, gdsjurisdiction, app } = this.props;
    if ((this.props.formData[0].sTbName === 'cahsupplyinit' && Object.keys(app.secondppopupPane).length === 0) || (this.props.formData[0].sTbName === 'cahcustomerinit' && Object.keys(app.secondppopupPane).length === 0) ||
      (this.props.formData[0].sTbName === 'cahcashierinit' && Object.keys(app.secondppopupPane).length === 0)) {
      // this.setState({ isShow: 'inline-block' });
    } else {
      // this.setState({ isShow: 'none' });
    }
    const mergeConfig = commonFunc.getConfigCondition(gdsconfigformslave, 'bVisible');
    const columns = [];
    const BtnOperations = gdsformconst.filter(item => (item.sName === 'BtnOperations'))[0].showName;
    // const BtnAdd = gdsformconst.filter(item => (item.sName === 'BtnAdd'))[0].showName;
    // const BtnRefresh = gdsformconst.filter(item => (item.sName === 'BtnRefresh'))[0].showName;
    // const BtnSetPeriod = gdsformconst.filter(item => (item.sName === 'BtnSetPeriod'))[0].showName;
    // const BtnRelievePeriod = gdsformconst.filter(item => (item.sName === 'BtnRelievePeriod'))[0].showName;
    const BtnUpd = gdsformconst.filter(item => (item.sName === 'BtnUpd'))[0].showName;
    const BtnDel = gdsformconst.filter(item => (item.sName === 'BtnDel'))[0].showName;
    const BtnSave = gdsformconst.filter(item => (item.sName === 'BtnSave'))[0].showName;
    const BtnCancel = gdsformconst.filter(item => (item.sName === 'BtnCancel'))[0].showName;
    // this.setState({
    //   BtnOperations, BtnAdd, BtnRefresh, BtnSetPeriod, BtnRelievePeriod, BtnUpd, BtnDel, BtnSave, BtnCancel,
    // });

    let childColumns = {};
    const dataRequired = {};
    let scrollX = 0;
    mergeConfig.map((child, i) => {
      if (child.bNotEmpty) {
        dataRequired[child.sName] = child.showName;
      }
      childColumns = {
        title: child.showName,
        dataIndex: child.sName,
        sorter: true,
        width: child.iFitWidth,
        render: (text, record) => this.renderColumns(text, record, child.sName),
      };
      scrollX += child.iFitWidth;
      this.setState({ scrollX });
      const indexLine = child.showName.indexOf('-');
      const title = child.showName.substr(indexLine + 1);
      const childTitle = child.showName.substr(0, indexLine);
      /* 此处判断为之前存在表头大类便进行合并 */
      const flag = i > 0 ? columns.filter(item => item.title === childTitle).length > 0 ? 1 : -1 : -1;
      if (indexLine > -1) {
        if (columns.length === 0 || flag === -1) {
          const obj = {
            title: childTitle,
            children: [{ ...childColumns, title }],
          };
          columns.push(obj);
        } else if (flag > -1) {
          /* 此处判断为之前存在表头大类便进行合并 */
          columns.filter(item => item.title === childTitle)[0].children.push({ ...childColumns, title });
        }
      } else {
        columns.push(childColumns);
      }
      return true;
    });

    const operation = {
      title: BtnOperations,
      dataIndex: 'BtnOperations',
      render: (text, record) => {
        const { disabledKey } = this.state;
        const editable = disabledKey !== record.key;
        return (
          <div className="editable-row-operations">
            {
              !editable ?
                <span className={styles.tableOperation}>
                  <button onClick={() => this.editDone(record.key, 'save')}>{BtnSave}</button>
                  <Popconfirm title="确定要取消?" onConfirm={() => this.editDone(record.key, 'cancel')}>
                    <button style={{ paddingLeft: 10 }}>{BtnCancel}</button>
                  </Popconfirm>
                </span>
                :
                <span className={styles.tableOperation}>
                  <button onClick={() => this.edit(record.key)}>{BtnUpd}</button>
                  <Popconfirm title="确定要删除?" onConfirm={() => this.onDelete(record.key)}>
                    <button style={{ paddingLeft: 10 }}>{BtnDel}</button>
                  </Popconfirm>
                </span>
            }
          </div>
        );
      },
    };
    columns.push(operation);
    this.setState({
      columns, tableConfig: { formData: this.props.config, gdsformconst, gdsjurisdiction }, mergeConfig, dataRequired,
    });
  }

  componentWillReceiveProps(nextProps) {
    const { dataList } = nextProps.content;
    const {
      sDataListTabId, componentName, pages, loading,
    } = dataList;
    if (nextProps.sTabId === sDataListTabId && this.state.componentName === componentName) {
      if (loading) {
        // this.setState({ loading: true });
      } else if (nextProps.data !== undefined && Object.keys(nextProps.data).length > 0) {
        const data = JSON.parse(JSON.stringify(nextProps.data));
        let index = 1;
        for (const value of data) {
          value.key = `${value.key}-${index}`;
          index += 1;
        }
        this.setState({
          data,
          pages,
          // loading: false,
        });
      }
    } else {
      const { data } = nextProps;
      this.setState({ data });
      if (nextProps.addRow) {
        this.handleBtnAdd();
      }
    }
  }

  shouldComponentUpdate(nextProps, nextState) {
    const { sTabId, componentName } = this.state;
    if (nextState.selectedRowKeys !== this.state.selectedRowKeys) return true;
    return nextProps.sTabId === sTabId && nextState.componentName === componentName;
  }

  onSelectChange = (selectedRowKeys) => {
    /* 选择数据 */
    this.setState({ selectedRowKeys });
    this.props.onSelectedRowKeys(selectedRowKeys);
  }

  onDelete = (key) => {
    const { tableConfig, isAdd, isEdit } = this.state;
    if (isAdd === true || isEdit === true) {
      return message.warning('请先完成正在操作的记录');
    }
    const { token } = this.props.app;
    const sActiveId = tableConfig.formData.sParentId;
    const sTableName = tableConfig.formData.sTbName;
    /* 支持表主从删除,视图主表删除 */
    const url = `${config.server_host}business/delMasSlaBusinessData?sModelsId=${sActiveId}`;
    const sId = key.indexOf('-') > -1 ? key.substr(0, key.indexOf('-')) : key;
    const value = {
      data: {
        sMasterTable: `${sTableName}`,
        sId: [sId],
      },
      sClientType: '1',
    };
    const options = {
      method: 'Post',
      headers: {
        'Content-Type': 'application/json',
        authorization: token,
      },
      body: JSON.stringify(value),
    };
    fetch(url, options).then(response => response.json()).then((json) => {
      if (json.code === 1) {
        message.success(json.msg);
        this.getData(config.pageNum, {}, {});
      } else {
        message.error(json.msg);
      }
    });
  }

  getData(pageNum, filters, sorter) {
    const { dataUrl, componentName } = this.state;
    const { sTabId, dispatch } = this.props;
    const sort = sorter.order === 'ascend' ? 'asc' : 'desc';
    const sFilterOrderBy = Object.keys(sorter).length > 0 ? { [sorter.columnKey]: sort } : ''; // 后端未支持空对象， 先用空表示
    const value = {
      bFilter: this.props.filterCondition,
      pageNum,
      pageSize: config.pageSize,
      sFilterOrderBy,
    };
    dispatch({
      type: 'content/getUrlPostData',
      payload: {
        url: dataUrl, sTabId, componentName, value, returnType: 'isGetData', formRoute: '/commonClassify',
      },
    });
  }

  handleDoubleClick = (record) => {
    const { ppopupPane, secondppopupPane } = this.props.app;
    /* 由于蒙层缘故，所以必然是先回带的二级弹窗，后续对蒙层改造时需要对弹窗也进行改造，可同时并存多个一级二级弹窗 */
    if (secondppopupPane !== undefined && Object.keys(secondppopupPane).length > 0 && secondppopupPane.modalType === 'ppopup') {
      /* resultFields为管理端配置的弹窗回带赋值值 */
      const { resultFields } = secondppopupPane;
      const resultValue = {};
      if (resultFields.length > 0) {
        resultFields.map((child) => {
          let recordKey = 'key';
          if (child.value.indexOf('[-]') > 0) {
            /* 处理弹窗回带根据配置key[-]value去拿值,而并不是根据sId[-]value去获值 */
            const spValue = child.value.split('[-]');
            if (spValue[0] === 'key' && record.key === undefined) {
              recordKey = 'sId';
            } else if (spValue[0] === 'sId' && record.sId === undefined) {
              recordKey = 'key';
            } else {
              [recordKey] = spValue;
            }
            let fieldKey = '';
            if ((recordKey === 'key' || recordKey === 'sId') && record[`${recordKey}`].indexOf('-') > -1) {
              fieldKey = record[`${recordKey}`].substr(0, record[`${recordKey}`].indexOf('-'));
            } else {
              fieldKey = record[`${recordKey}`];
            }
            resultValue[`${child.key}`] = `${fieldKey}[-]${record[`${spValue[1]}`]}`;
          } else {
            resultValue[`${child.key}`] = record[`${child.value}`];
          }
          return '';
        });
      }
      /* 赋值回带如果出现回带给主表同时需要回带给从表将需要额外改造，目前并未能适配 */
      this.props.handleGetSelfResult(resultValue);
    } else if (Object.keys(ppopupPane).length > 0 && ppopupPane.modalType === 'ppopup') {
      /* resultFields为管理端配置的弹窗回带赋值值 */
      const { resultFields } = ppopupPane;
      const resultValue = {};
      if (resultFields.length > 0) {
        resultFields.map((child) => {
          let recordKey = 'key';
          if (child.value.indexOf('[-]') > 0) {
            /* 处理弹窗回带根据配置key[-]value去拿值,而并不是根据sId[-]value去获值 */
            const spValue = child.value.split('[-]');
            if (spValue[0] === 'key' && record.key === undefined) {
              recordKey = 'sId';
            } else if (spValue[0] === 'sId' && record.sId === undefined) {
              recordKey = 'key';
            } else {
              [recordKey] = spValue;
            }
            let fieldKey = '';
            if ((recordKey === 'key' || recordKey === 'sId') && record[`${recordKey}`].indexOf('-') > -1) {
              fieldKey = record[`${recordKey}`].substr(0, record[`${recordKey}`].indexOf('-'));
            } else {
              fieldKey = record[`${recordKey}`];
            }
            resultValue[`${child.key}`] = `${fieldKey}[-]${record[`${spValue[1]}`]}`;
          } else {
            resultValue[`${child.key}`] = record[`${child.value}`];
          }
          return '';
        });
      }
      /* 赋值回带如果出现回带给主表同时需要回带给从表将需要额外改造，目前并未能适配 */
      this.props.handleGetResult(resultValue);
    }
  }

  handleBtnAdd = () => {
    const { isEdit, isAdd } = this.state;
    if (isAdd === true || isEdit === true) {
      /* 关闭新增开关 */
      this.props.changeAddRow();
      return message.warning('请先完成正在操作的记录');
    }
    /* 获取唯一Id */
    const { token } = this.props.app;
    const url = `${config.server_host}getUuid`;
    const options = {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        authorization: token,
      },
    };
    fetch(url, options).then(response => response.json()).then((json) => {
      const key = json.dataset.rows[0];
      const { data } = this.state;
      const newData = {
        key,
      };
      /* 通用分类上操作行ID */
      if (this.props.handleTableData !== undefined) {
        /* 关闭新增开关 */
        this.props.changeAddRow();
        this.props.handleTableData([newData, ...data]);
        this.props.handleRecordKey(key);
      }
      this.setState({
        // isDisabled: true,
        isAdd: true,
        // sId: key,
        data: [newData, ...data],
        disabledKey: key,
      });
    });
  };

  handleBtnRefresh = () => {
    const { isAdd, isEdit } = this.state;
    if (isAdd === true || isEdit === true) {
      return message.warning('请先完成正在操作的记录');
    }
    this.getData(config.pageNum, {}, {});
  };

  handleBtnSetPeriod = () => {
    const { tableConfig } = this.state;
    const { token } = this.props.app;
    const sActiveId = tableConfig.formData.sParentId;
    let changeValue = '';
    if (this.props.app.currentPane.route === '/supplyCommonClassify') {
      changeValue = 'bAP';
    } else if (this.props.app.currentPane.route === '/customerCommonClassify') {
      changeValue = 'bAR';
    } else if (this.props.app.currentPane.route === '/cashierCommonClassify') {
      changeValue = 'bCashier';
    }
    const url = `${config.server_host}sysAccountPeriod/updateSysAccountPeriod?sModelsId=${sActiveId}`;
    const value = { sClientType: '1', handleType: 'add', sClomunType: changeValue };
    const options = {
      method: 'Post',
      headers: {
        'Content-Type': 'application/json',
        authorization: token,
      },
      body: JSON.stringify(value),
    };
    fetch(url, options).then(response => response.json()).then((json) => {
      if (json.code === 1) {
        message.success(json.msg);
      } else {
        message.error(json.msg);
      }
    });
  };

  handleBtnRelievePeriod = () => {
    const { tableConfig } = this.state;
    const { token } = this.props.app;
    const sActiveId = tableConfig.formData.sParentId;
    let changeValue = '';
    if (this.props.app.currentPane.route === '/supplyCommonClassify') {
      changeValue = 'bAP';
    } else if (this.props.app.currentPane.route === '/customerCommonClassify') {
      changeValue = 'bAR';
    } else if (this.props.app.currentPane.route === '/cashierCommonClassify') {
      changeValue = 'bCashier';
    }
    const url = `${config.server_host}sysAccountPeriod/updateSysAccountPeriod?sModelsId=${sActiveId}`;
    const value = { sClientType: '1', handleType: 'reset', sClomunType: changeValue };
    const options = {
      method: 'Post',
      headers: {
        'Content-Type': 'application/json',
        authorization: token,
      },
      body: JSON.stringify(value),
    };
    fetch(url, options).then(response => response.json()).then((json) => {
      if (json.code === 1) {
        message.success(json.msg);
      } else {
        message.error(json.msg);
      }
    });
  };


  edit = (key) => {
    const { isEdit, isAdd } = this.state;
    const { gdsformconst } = this.props;
    /* 通用分类上操作行ID */
    /* if (this.props.handleSelf !== undefined) {
      this.props.handleRecordKey(key);
    } */
    this.props.handleRecordKey(key);
    if (isAdd === true || isEdit === true) {
      const textName = gdsformconst.filter(item => (item.sName === 'completebeingOperated'))[0].showName;
      return message.warning(textName);
    } else {
      this.setState({
        isEdit: true,
        disabledKey: key,
      });
    }
  };

  editDone(key, type) {
    const {
      data, isAdd, isEdit, tableConfig, dataRequired,
    } = this.state;
    if (type === 'cancel') {
      if (this.state.isAdd === true) {
        data.splice(0, 1);
      }
      this.setState({
        isAdd: false,
        isEdit: false,
        // addisabled: false,
        disabledKey: '',
        // sId: '',
        data,
      });
    } else if (type === 'save') {
      const textName = tableConfig.gdsformconst.filter(item => (item.sName === 'required'))[0].showName;
      let flag = 0;
      const recordData = data.filter(item => (item.key === key))[0];
      Object.keys(dataRequired).forEach((child) => {
        if (Object.keys(recordData).indexOf(child) < 0) {
          flag = 1;
          message.warning(`${textName}【${dataRequired[child]}】`);
        }
      });
      if (flag !== 1) {
        /* 数据添加 */
        const column = {};
        Object.keys(recordData).forEach((item) => {
          if (item !== 'BtnOperations') {
            if (item === 'key') {
              column.sId = recordData[item];
            } else {
              column[item] = recordData[item];
            }
          }
        });
        if (isAdd === true) {
          column.handleType = 'add';
        }
        if (isEdit === true) {
          column.handleType = 'update';
        }
        const { token } = this.props.app;
        const sActiveId = tableConfig.formData.sParentId;
        const sTableName = tableConfig.formData.sTbName;
        const url = `${config.server_host}business/addUpdateDelBusinessData?sModelsId=${sActiveId}`;
        const value = {
          data: [{
            sTable: `${sTableName}`,
            column: [column],
          }],
          sClientType: '1',
        };
        const options = {
          method: 'Post',
          headers: {
            'Content-Type': 'application/json',
            authorization: token,
          },
          body: JSON.stringify(value),
        };
        fetch(url, options).then(response => response.json()).then((json) => {
          if (json.code === 1) {
            message.success(json.msg);
            this.setState({
              isAdd: false,
              isEdit: false,
              // addisabled: false,
              // sId: '',
              disabledKey: '',
            });
            this.getData(config.pageNum, {}, {});
          } else {
            message.error(json.msg);
          }
        });
      }
    }
  }

  handleTableChange = (pagination, filters, sorter) => {
    const { isEdit, isAdd } = this.state;
    if (isAdd === true || isEdit === true) {
      return message.warning('请先完成正在操作的记录');
    }
    /* 表分页，排序，筛选时的变化，后台抓取数据 */
    this.getData(pagination.current, filters, sorter);
  }

  handleChange(value, record, column, resultFields) {
    const newData = this.state.data;
    const target = newData.filter(item => record === item.key)[0];
    if (target) {
      /* 过滤掉ppopupValue赋值,只保留handleType */
      if (value !== 'ppopupValue') {
        /* 存在赋值回带一般为下拉情况下 */
        if (resultFields !== undefined && resultFields !== '') {
          for (const item of resultFields) {
            /* 数据处理,手动清空数据时数据会为undefined，不符合数据赋值要求 */
            const resultValue = {};
            let itemVlaue = '';
            /* 列表中的时间控件清空不会自动重置为NULL,需要手动处理避免影响默认值 */
            if (`${item.key}`.startsWith('t') && item.value === '') {
              itemVlaue = null;
            } else {
              itemVlaue = item.value;
            }
            resultValue[`${item.key}`] = itemVlaue;
            const result = commonFunc.changeValue(resultValue);
            target[`${item.key}`] = result[`${item.key}`];
          }
        }
        /* 数据处理,手动清空数据时数据会为undefined，不符合数据赋值要求 */
        const resultValue = {};
        /* 列表中的时间控件清空不会自动重置为NULL,需要手动处理避免影响默认值 */
        if (column.startsWith('t') && value === '') {
          value = null;
        }
        resultValue[`${column}`] = value;
        const result = commonFunc.changeValue(resultValue);
        target[`${column}`] = result[`${column}`];
      }
      if (target.handleType === undefined) {
        target.handleType = 'update';
      }
      this.setState({ data: newData });
    }
  }

  renderColumns = (text, record, column) => {
    const { mergeConfig, disabledKey, sActiveId } = this.state;
    let disabledState = true;
    if (record.key === disabledKey) {
      disabledState = false;
    }
    const showConfig = mergeConfig.filter(item => (item.sName === column))[0];
    /* 列表默认值 */
    const columnValue = commonFunc.listDefaultValue(showConfig, text);
    const editTableProps = {
      sActiveId,
      editable: true,
      value: columnValue,
      showConfig,
      disabled: disabledState,
      app: this.props.app,
      form: this.props.form,
      handleModalPane: this.props.handleModalPane,
      handleSelf: true, /* 弹出框是否是通用分类弹出框 */
      sTabId: this.props.sTabId, /* 二级弹窗使用父类sTabId作为自己key */
    };
    return (<ShowType
      sName={column}
      {...editTableProps}
      onChange={(value, resultFields) => this.handleChange(value, record.key, column, resultFields)}
    />);
  }

  render() {
    const {
      data, columns, pages, selectedRowKeys, scrollX,
    } = this.state;
    const rowSelection = {
      type: 'checkbox',
      selectedRowKeys,
      onChange: this.onSelectChange,
    };
    return (
      <div>
        <Table
          columns={columns}
          dataSource={data}
          rowSelection={rowSelection}
          bordered
          pagination={{
            defaultPageSize: config.pageSize,
            pageSize: config.pageSize,
            total: pages.totalCount,
            showQuickJumper: true,
            current: pages.pageNum,
            className: `${styles.pagination}`,
          }}
          size="middle"
          onChange={this.handleTableChange}
          onRow={(record) => { return { onDoubleClick: () => { this.handleDoubleClick(record); } }; }}
          scroll={{ x: scrollX }}
        />
      </div>
    );
  }
}
const MergeTableEditComponent = Form.create()(MergeTableEdit);
export default MergeTableEditComponent;
